#include "stockoperationdialog.h"
#include "ui_stockoperationdialog.h"
#include <QDebug>

StockOperationDialog::StockOperationDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::StockOperationDialog)
    , m_operationType("入库")
{
    ui->setupUi(this);
    
    // 设置窗口属性
    setWindowTitle("库存操作");
    setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
    setModal(true);
    resize(450, 250);
    
    // 设置操作数量输入框的范围
    ui->quantitySpinBox->setRange(1, 9999);
    ui->quantitySpinBox->setValue(1);
    
    // 连接信号槽
    connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &StockOperationDialog::onAccepted);
    connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &StockOperationDialog::onRejected);
    connect(ui->itemComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), 
            this, &StockOperationDialog::onItemChanged);
    
    // 加载物品列表
    loadItems();
}

StockOperationDialog::~StockOperationDialog()
{
    delete ui;
}

// 设置操作类型（"入库" 或 "出库"）
void StockOperationDialog::setOperationType(const QString& type)
{
    m_operationType = type;
    setWindowTitle(QString("%1操作").arg(type));
    ui->operationTypeLabel->setText(QString("操作类型: %1").arg(type));
    
    // 根据操作类型设置样式
    if (type == "入库") {
        ui->operationTypeLabel->setStyleSheet("color: #28a745; font-weight: bold;");
    } else if (type == "出库") {
        ui->operationTypeLabel->setStyleSheet("color: #dc3545; font-weight: bold;");
    }
}

// 设置预选物品
void StockOperationDialog::setSelectedItem(const ItemInfo& item)
{
    m_selectedItem = item;
    
    // 在下拉框中选中对应物品
    for (int i = 0; i < ui->itemComboBox->count(); ++i) {
        if (ui->itemComboBox->itemData(i).toInt() == item.id) {
            ui->itemComboBox->setCurrentIndex(i);
            break;
        }
    }
}

// 设置当前用户
void StockOperationDialog::setCurrentUser(const UserInfo& user)
{
    m_currentUser = user;
    ui->operatorLabel->setText(QString("操作员: %1").arg(user.username));
}

// 加载物品到下拉框
void StockOperationDialog::loadItems()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    m_items = dbManager.getAllItems();
    
    ui->itemComboBox->clear();
    ui->itemComboBox->addItem("请选择物品...", -1);
    
    for (const ItemInfo& item : m_items) {
        QString displayText = QString("%1 (%2)").arg(item.name, item.model);
        ui->itemComboBox->addItem(displayText, item.id);
    }
    
    // 默认选择第一项（请选择物品...）
    ui->itemComboBox->setCurrentIndex(0);
    updateCurrentStock();
}

// 更新当前库存显示
void StockOperationDialog::updateCurrentStock()
{
    int selectedIndex = ui->itemComboBox->currentIndex();
    if (selectedIndex <= 0) {
        ui->currentStockLabel->setText("当前库存: --");
        ui->locationLabel->setText("存放位置: --");
        return;
    }
    
    int itemId = ui->itemComboBox->itemData(selectedIndex).toInt();
    
    // 查找对应的物品信息
    for (const ItemInfo& item : m_items) {
        if (item.id == itemId) {
            ui->currentStockLabel->setText(QString("当前库存: %1 件").arg(item.quantity));
            ui->locationLabel->setText(QString("存放位置: %1").arg(item.location));
            
            // 如果是出库且库存不足，显示警告
            if (m_operationType == "出库" && item.quantity < ui->quantitySpinBox->value()) {
                ui->currentStockLabel->setStyleSheet("color: #dc3545; font-weight: bold;");
            } else {
                ui->currentStockLabel->setStyleSheet("color: #28a745; font-weight: bold;");
            }
            break;
        }
    }
}

// 物品选择变化
void StockOperationDialog::onItemChanged(int index)
{
    Q_UNUSED(index)
    updateCurrentStock();
}

// 验证操作
bool StockOperationDialog::validateOperation()
{
    // 检查是否选择了物品
    if (ui->itemComboBox->currentIndex() <= 0) {
        QMessageBox::warning(this, "输入错误", "请选择要操作的物品！");
        ui->itemComboBox->setFocus();
        return false;
    }
    
    // 检查操作数量
    int quantity = ui->quantitySpinBox->value();
    if (quantity <= 0) {
        QMessageBox::warning(this, "输入错误", "操作数量必须大于0！");
        ui->quantitySpinBox->setFocus();
        return false;
    }
    
    // 如果是出库操作，检查库存是否充足
    if (m_operationType == "出库") {
        int itemId = ui->itemComboBox->itemData(ui->itemComboBox->currentIndex()).toInt();
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        
        if (!dbManager.checkStockAvailable(itemId, quantity)) {
            ItemInfo item = dbManager.getItemById(itemId);
            QMessageBox::warning(this, "库存不足", 
                QString("库存不足！\n当前库存: %1 件\n出库数量: %2 件")
                .arg(item.quantity).arg(quantity));
            ui->quantitySpinBox->setFocus();
            return false;
        }
    }
    
    return true;
}

// 执行库存操作
bool StockOperationDialog::performStockOperation()
{
    int itemId = ui->itemComboBox->itemData(ui->itemComboBox->currentIndex()).toInt();
    int quantity = ui->quantitySpinBox->value();
    
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    
    // 计算库存变化量
    int quantityChange = (m_operationType == "入库") ? quantity : -quantity;
    
    // 添加操作记录
    if (!dbManager.addStockRecord(itemId, m_operationType, quantity, m_currentUser.id)) {
        QMessageBox::critical(this, "错误", "添加操作记录失败！");
        return false;
    }
    
    // 更新物品库存
    if (!dbManager.updateItemQuantity(itemId, quantityChange)) {
        QMessageBox::critical(this, "错误", "更新库存数量失败！");
        return false;
    }
    
    return true;
}

// 确定按钮点击
void StockOperationDialog::onAccepted()
{
    if (!validateOperation()) {
        return;
    }
    
    // 确认操作
    int itemId = ui->itemComboBox->itemData(ui->itemComboBox->currentIndex()).toInt();
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    ItemInfo item = dbManager.getItemById(itemId);
    
    int ret = QMessageBox::question(this, "确认操作", 
        QString("确定要执行以下操作吗？\n\n"
                "物品: %1\n"
                "操作: %2\n"
                "数量: %3 件\n"
                "操作员: %4")
        .arg(item.name)
        .arg(m_operationType)
        .arg(ui->quantitySpinBox->value())
        .arg(m_currentUser.username),
        QMessageBox::Yes | QMessageBox::No);
    
    if (ret != QMessageBox::Yes) {
        return;
    }
    
    // 执行操作
    if (performStockOperation()) {
        QMessageBox::information(this, "成功", 
            QString("%1操作执行成功！").arg(m_operationType));
        accept();
    }
}

// 取消按钮点击
void StockOperationDialog::onRejected()
{
    reject();
}